<?php

namespace app\admin\controller;

use think\facade\View;
use think\facade\Request;
use think\facade\Session;
use think\facade\Config;
use think\facade\Db;
use auth\Auth;
use common\Tree;
use app\admin\model\Category as categoryModel;
use app\common\controller\AppCommon;

class Common extends AppCommon
{


    protected $middleware = ['\app\middleware\LoginCheck', '\app\middleware\AdminAuth'];

    public $moduleFields = array();

    /**
     * 构造方法
     * @access public
     */
    public function __construct()
    {
		parent::__construct();
        self::viewFilter();
        self::setAssign();
//        $this->moduleFields = self::getModuleFields();
    }




    /**
     * 模板变量赋值
     * @param string|array $name 变量名称或者数组
     * @param string $value 值
     * @return null
     */
    public function assign($name, $value = '')
    {
        if (is_array($name) && empty($value)) {
            View::assign($name);
        } else {
            View::assign($name, $value);
        }
    }


    /**
     * 全局模板过滤替换
     * @param string|array $name 变量名称或者数组
     * @param string $value 值
     * @return null
     */
    static public function viewFilter()
    {
        View::filter(function ($content) {
            $config = config("template.tpl_replace_string");
            if (is_array($config)) {
                foreach ($config as $key => $one) {
                    $content = str_replace($key, $one, $content);
                }
            }
            return $content;
        });
    }

    /**
     * 公共分类管理列表
     * @return null
     */
    public function category()
    {
        try {
            if (request()->isPost()) {
                $model = strtolower(CONTROLLER);
                $keyword = input('request.keyword', 0);
                $where = array();
                $where[] = ['model', '=', $model];
                if (!empty($keyword)) {
                    $where[] = ['title', 'like', '%' . urldecode($keyword) . '%'];
                    $this->assign($keyword);
                }

                $Tree = new Tree();
                $cateList = Db::name('category')->where($where)->order("sort", "asc")->select()->toArray();
                $categorys = $Tree->cate($cateList);
                return ['code' => 0, 'msg' => '获取成功！', 'data' => $categorys, 'rel' => 1];
            } else {
                $path = config("view.view_path") . strtolower(CONTROLLER) . "/" . strtolower(ACTION) . "." . config("view.view_suffix");
                if (file_exists($path)) {
                    return View::fetch($path);
                } else {
                    $path = config("view.view_path") . "public/" . strtolower(ACTION) . "." . config("view.view_suffix");
                    return View::fetch($path);
                }
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 添加分类
     * @return null
     */
    public function categoryAdd()
    {
        try {
            $Tree = new Tree();
            $cateList = Db::name('category')->where("model", strtolower(CONTROLLER))->order("sort", "asc")->select()->toArray();
            $categorys = $Tree->cate($cateList);
            $this->assign('categorys', $categorys);

            if (Request::isPost()) {
                $data = input('post.');
                $data['create_time'] = time();
                $data['model'] = strtolower(CONTROLLER);
                categoryModel::addCategory($data);
                return ['code' => 0, 'msg' => '添加成功！'];
            } else {
                $path = config("view.view_path") . strtolower(CONTROLLER) . "/categoryedit." . config("view.view_suffix");
                if (file_exists($path)) {
                    return View::fetch($path);
                } else {
                    $path = config("view.view_path") . "public/categoryedit." . config("view.view_suffix");
                    return View::fetch($path);
                }
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 编缉分类
     * @return null
     */
    public function categoryEdit()
    {
        try {
            $Tree = new Tree();
            $cateList = Db::name('category')->where("model", strtolower(CONTROLLER))->order("sort", "asc")->select()->toArray();
            $categorys = $Tree->cate($cateList);
            $this->assign('categorys', $categorys);

            if (request()->isPost()) {
                $data = input('post.');
                $data['update_time'] = time();
                if ($data['id'] == $data['pid']) {
                    return ['code' => 2000, 'msg' => '不能选择自己做父类！'];
                }
                categoryModel::edit($data['id'],$data);
                return ['code' => 0, 'msg' => '修改成功！'];
            } else {
                $id = input('id', 0, "intval");
                if (!$id) {
                    return ['code' => 2000, 'msg' => '非法请求！'];
                }
                $info = categoryModel::find(['id' => $id]);
                $this->assign('info', $info);
                $path = config("view.view_path") . strtolower(CONTROLLER) . "/categoryedit." . config("view.view_suffix");
                if (file_exists($path)) {
                    return View::fetch($path);
                } else {
                    $path = config("view.view_path") . "public/categoryedit." . config("view.view_suffix");
                    return View::fetch($path);
                }
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 分类列表修改
     * @param $id 主键
     * @param $status 值
     * @return Array
     */
    public function categoryListEdit()
    {
        try {
            $data = input('param.');
            if (categoryModel::update($data)) {
                return ['code' => 0, 'msg' => '修改成功！'];
            } else {
                return ['code' => 1, 'msg' => '修改失败！'];
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }


    /**
     * 分类删除
     * @param $id 主键
     * @param $status 值
     * @return Array
     */
    public function categoryDelete()
    {
        try {
            $id = input('request.id');
            if (!$id) {
                return ['code' => 3000, 'msg' => '请选择要删除的数据!'];
            }
            //$result = Db::name("category")->where("id", $id)->delete();
            $result=categoryModel::destroy($id);
            if ($result) {
                return ['code' => 0, 'msg' => '操作成功!'];
            }
            return ['code' => 3000, 'msg' => '操作失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 更改分类状态
     * @param $id 主键
     * @param $status 值
     * @return Array
     */
    public function doCategoryStatus()
    {
        try {
            $id = input('request.id');
            $status = input('request.status');
            if (!$id) {
                return ['code' => 3000, 'msg' => '操作失败!'];
            }
            $result = Db::name("category")->where("id", $id)->update(['status' => $status]);
            if ($result) {
                return ['code' => 0, 'msg' => '操作成功!'];
            }
            return ['code' => 3000, 'msg' => '操作失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }

    }


    /**
     * 更改状态
     * @param $id 主键
     * @param $status 值
     * @return Array
     */
    public function doStatus()
    {
        try {
            $id = input('request.id');
            $status = input('request.status');
            if (!$id) {
                return ['code' => 3000, 'msg' => '操作失败!'];
            }
            $result = Db::name(CONTROLLER)->where("id", $id)->update(['status' => $status]);
            if ($result) {
                return ['code' => 0, 'msg' => '操作成功!'];
            }
            return ['code' => 3000, 'msg' => '操作失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 删除数据
     * @param $id 主键
     * @return Array
     */
    public function doDelete()
    {
        try {
            $id = input('request.id');
            if (!$id) {
                return ['code' => 3000, 'msg' => '请选择要删除的数据!'];
            }
            $result = Db::name(CONTROLLER)->where("id", $id)->delete();
            if ($result) {
                return ['code' => 0, 'msg' => '操作成功!'];
            }
            return ['code' => 3000, 'msg' => '操作失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }

    }

    /**
     * 批量删除
     * @param $ids 主键
     * @return Array
     */
    public function doDeleteAll()
    {
        try {
            $ids = input('ids');
            if (!$ids) {
                return ['code' => 3000, 'msg' => '请选择要删除的数据!'];
            }
            $result = Db::name(CONTROLLER)->where("id", "in", $ids)->delete();
            if ($result) {
                return ['code' => 0, 'msg' => '操作成功!'];
            }
            return ['code' => 3000, 'msg' => '操作失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }

    }

    /**
     * 赋值所有接收到的参数到模板变量
     * @author admin
     * @date 2018-03-18
     */
    private function setAssign()
    {
        $arr = input('request.'); //get,post,cookies等请求参数
        $request = request();
        $param = $request->param(); //请求参数
        $this->assign($arr); //赋值到模板
        $this->assign($param);
        $this->assign("sys_path", SYS_PATH);
    }

    /**
     * 获取模型里面的所有字段
     * @author admin
     * @date 2018-03-18
     */
    private function getModuleFields()
    {
        $fields = Db::name("module")
						->field("b.*")
						->alias("a")
						->join("field b", "a.id=b.moduleid", "LEFT")
						->where("a.name", strtolower(CONTROLLER))
						->order("sort", 'asc')
						->select()->toArray();
        $return = array();
        if ($fields) {
            foreach ($fields as $key => $one) {
                $return[$one['field']] = $one;
            }
            $this->assign("fields", $return);
            return $return;
        }
        return false;
    }

    /**
     * @param $user_agent_id
     * @param int $type 1所有下级。不然只获取自己的下级
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNextAgentIds($user_agent_id,$type = 1){
        if ($type=1){
            $agents = self::getNextAgent($user_agent_id);
        }else{
            $agents = Db::name('user_agent')
                ->order('user_agent_id','asc')
                ->where('parent_id',$user_agent_id)
                ->select()
                ->toArray();
        }
        $str = '';
        foreach ($agents as $k => $v){
            $str .= $v['user_agent_id'].',';
        }
        $str = rtrim($str,',');
        return $str;
    }

    /**
     * 获取代理ID下面的所有用户
     * @param $user_agent_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNextUsers($user_agent_id){
        $agentsIds = self::getNextAgentIds($user_agent_id);
        return Db::name('user')->whereIn('user_agent_id',$agentsIds)->select()->toArray();
    }

    /**
     * 获取下级代理 包括自己
     * @param $user_agent_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNextAgent($user_agent_id){
        return Db::name('user_agent')
            ->field('user_agent_id')
            ->order('user_agent_id','asc')
            ->whereFindInSet('parent_tree', $user_agent_id)
            ->whereOr('user_agent_id',$user_agent_id)
            ->select()->toArray();
    }

    /**
     * 检查模型里面的字段类型，数据转换
     * @author admin
     * @date 2018-03-18
     */
    public function checkfield($fields, $data)
    {
        if (empty($fields)) return $data;
        foreach ($data as $key => $val) {
            if (isset($fields[$key])) {
                if ($fields[$key]['type'] == 'datetime') {
                    $data[$key] = strtotime($data[$key]);
                }
            }
        }
        return $data;
    }


}
